package com.yjj.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yjj.springboot3.model.dto.conversation.ConversationQueryRequest;
import com.yjj.springboot3.model.entity.Conversation;
import com.yjj.springboot3.model.entity.User;
import com.yjj.springboot3.model.json.ChatMessage;
import com.yjj.springboot3.model.json.ChatMessageList;
import com.yjj.springboot3.model.vo.AdminConversationVO;
import com.yjj.springboot3.model.vo.ConversationListVO;
import com.yjj.springboot3.model.vo.MessageListVO;
import com.yjj.springboot3.service.ConversationService;
import com.yjj.springboot3.mapper.ConversationMapper;
import com.yjj.springboot3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 王洪顺
* @description 针对表【conversation(对话)】的数据库操作Service实现
* @createDate 2025-09-02 20:03:38
*/
@Service
@Slf4j
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation>
    implements ConversationService{

    @Autowired
    private UserService userService;

    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 解析消息JSON，支持ChatMessageList和List<ChatMessage>两种格式
     */
    private List<ChatMessage> parseMessages(String messageJson) throws Exception {
        if (StringUtils.isBlank(messageJson)) {
            return new ArrayList<>();
        }
        
        try {
            // 先尝试解析为ChatMessageList对象
            ChatMessageList messageList = objectMapper.readValue(messageJson, ChatMessageList.class);
            return messageList.getMessages() != null ? messageList.getMessages() : new ArrayList<>();
        } catch (Exception e) {
            // 如果解析ChatMessageList失败，尝试直接解析为List<ChatMessage>（兼容旧数据）
            try {
                return objectMapper.readValue(messageJson, new TypeReference<List<ChatMessage>>() {});
            } catch (Exception ex) {
                log.warn("消息JSON格式无法识别，返回空列表。JSON: {}", messageJson);
                return new ArrayList<>();
            }
        }
    }

    @Override
    public boolean saveOrUpdateConversation(Long conversationId, String messageJson) {
        try {
            // 先尝试查找现有的对话记录
            Conversation existingConversation = this.getById(conversationId);
            
            if (existingConversation != null) {
                // 更新现有对话
                existingConversation.setMessage(messageJson);
                existingConversation.setStatus(1); // 对话中
                existingConversation.setUpdateTime(new Date());
                return this.updateById(existingConversation);
            } else {
                // 理论上不应该到这里，因为会话应该已经存在
                // 但为了容错，还是创建新对话
                Conversation newConversation = new Conversation();
                newConversation.setId(conversationId);
                newConversation.setMessage(messageJson);
                newConversation.setStatus(1); // 对话中
                newConversation.setCreateTime(new Date());
                newConversation.setUpdateTime(new Date());
                newConversation.setIsDelete(0);
                return this.save(newConversation);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public QueryWrapper<Conversation> getQueryWrapper(ConversationQueryRequest conversationQueryRequest) {
        QueryWrapper<Conversation> queryWrapper = new QueryWrapper<>();
        if (conversationQueryRequest == null) {
            return queryWrapper;
        }

        Long conversationId = conversationQueryRequest.getConversationId();
        Long userId = conversationQueryRequest.getUserId();
        Integer status = conversationQueryRequest.getStatus();

        // 根据条件构建查询
        queryWrapper.eq(conversationId != null, "id", conversationId);
        queryWrapper.eq(userId != null, "userId", userId);
        queryWrapper.eq(status != null, "status", status);
        queryWrapper.orderByDesc("updateTime");

        return queryWrapper;
    }

    @Override
    public List<ConversationListVO> getUserConversationList(Long userId, long current, long pageSize) {
        try {
            // 查询用户的对话列表
            QueryWrapper<Conversation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userId", userId);
            queryWrapper.orderByDesc("updateTime");
            
            // 分页查询
            Page<Conversation> page = new Page<>(current, pageSize);
            Page<Conversation> conversationPage = this.page(page, queryWrapper);
            
            // 转换为VO
            return conversationPage.getRecords().stream().map(conversation -> {
                ConversationListVO vo = new ConversationListVO();
                vo.setConversationId(conversation.getId());
                vo.setStatus(conversation.getStatus());
                vo.setCreateTime(conversation.getCreateTime());
                vo.setUpdateTime(conversation.getUpdateTime());
                
                // 解析消息生成标题和消息数量
                String title = "新对话";
                int messageCount = 0;
                
                if (StringUtils.isNotBlank(conversation.getMessage())) {
                    try {
                        List<ChatMessage> messages = parseMessages(conversation.getMessage());
                        messageCount = messages.size();
                        
                        // 取第3条用户消息作为标题（前30个字符）
                        int index = 1;
                        for (ChatMessage message : messages) {
                            if ("USER".equalsIgnoreCase(message.getType()) && StringUtils.isNotBlank(message.getContent())&& index == 3) {
                                title = message.getContent().length() > 30 ? 
                                        message.getContent().substring(0, 30) + "..." : 
                                        message.getContent();
                                break;
                            }
                            index++;
                        }
                    } catch (Exception e) {
                        log.error("解析对话消息失败，对话ID: {}", conversation.getId(), e);
                    }
                }
                
                vo.setTitle(title);
                vo.setMessageCount(messageCount);
                return vo;
            }).collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取用户对话列表失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public MessageListVO getMessageList(Long conversationId, Long userId) {
        try {
            // 验证对话是否存在且属于当前用户
            Conversation conversation = this.getById(conversationId);
            if (conversation == null || conversation.getIsDelete() == 1 || !conversation.getUserId().equals(userId)) {
                return null;
            }
            
            MessageListVO vo = new MessageListVO();
            vo.setConversationId(conversationId);
            vo.setStatus(conversation.getStatus());
            vo.setCreateTime(conversation.getCreateTime());
            vo.setUpdateTime(conversation.getUpdateTime());
            
            // 解析消息
            List<ChatMessage> messages = new ArrayList<>();
            if (StringUtils.isNotBlank(conversation.getMessage())) {
                try {
                    messages = parseMessages(conversation.getMessage());
                } catch (Exception e) {
                    log.error("解析对话消息失败，对话ID: {}", conversationId, e);
                }
            }
            
            vo.setMessages(messages);
            vo.setTotalCount(messages.size());
            return vo;
            
        } catch (Exception e) {
            log.error("获取消息列表失败，对话ID: {}, 用户ID: {}", conversationId, userId, e);
            return null;
        }
    }

    @Override
    public boolean deleteUserConversation(Long conversationId, Long userId) {
        try {
            // 验证对话是否存在且属于当前用户
            Conversation conversation = this.getById(conversationId);
            if (conversation == null || conversation.getIsDelete() == 1 || !conversation.getUserId().equals(userId)) {
                return false;
            }
            
            // 逻辑删除
            conversation.setIsDelete(1);
            conversation.setUpdateTime(new Date());
            return this.updateById(conversation);
            
        } catch (Exception e) {
            log.error("删除用户对话失败，对话ID: {}, 用户ID: {}", conversationId, userId, e);
            return false;
        }
    }

    @Override
    public Page<AdminConversationVO> getAdminConversationPage(ConversationQueryRequest queryRequest) {
        try {
            // 设置默认分页参数
            long current = queryRequest.getCurrent() > 0 ? queryRequest.getCurrent() : 1;
            long pageSize = queryRequest.getPageSize() > 0 ? queryRequest.getPageSize() : 10;
            
            // 构建查询条件
            QueryWrapper<Conversation> queryWrapper = getQueryWrapper(queryRequest);
            
            // 分页查询
            Page<Conversation> page = new Page<>(current, pageSize);
            Page<Conversation> conversationPage = this.page(page, queryWrapper);
            
            // 转换为AdminConversationVO
            Page<AdminConversationVO> result = new Page<>(current, pageSize, conversationPage.getTotal());
            List<AdminConversationVO> adminVOList = conversationPage.getRecords().stream().map(conversation -> {
                AdminConversationVO vo = new AdminConversationVO();
                vo.setConversationId(conversation.getId());
                vo.setUserId(conversation.getUserId());
                vo.setStatus(conversation.getStatus());
                vo.setCreateTime(conversation.getCreateTime());
                vo.setUpdateTime(conversation.getUpdateTime());
                
                // 获取用户信息
                User user = userService.getById(conversation.getUserId());
                if (user != null) {
                    vo.setUserName(user.getUserName());
                    vo.setUserAccount(user.getUserAccount());
                }
                
                // 解析消息生成标题和消息数量
                String title = "新对话";
                int messageCount = 0;
                
                if (StringUtils.isNotBlank(conversation.getMessage())) {
                    try {
                        List<ChatMessage> messages = parseMessages(conversation.getMessage());
                        messageCount = messages.size();
                        
                        // 取第一条用户消息作为标题（前30个字符）
                        for (ChatMessage message : messages) {
                            if ("USER".equalsIgnoreCase(message.getType()) && StringUtils.isNotBlank(message.getContent())) {
                                title = message.getContent().length() > 30 ? 
                                        message.getContent().substring(0, 30) + "..." : 
                                        message.getContent();
                                break;
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析对话消息失败，对话ID: {}", conversation.getId(), e);
                    }
                }
                
                vo.setTitle(title);
                vo.setMessageCount(messageCount);
                return vo;
            }).collect(Collectors.toList());
            
            result.setRecords(adminVOList);
            return result;
            
        } catch (Exception e) {
            log.error("管理员获取对话列表失败", e);
            return new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize(), 0);
        }
    }

    @Override
    public boolean adminDeleteConversation(Long conversationId) {
        try {
            Conversation conversation = this.getById(conversationId);
            if (conversation == null || conversation.getIsDelete() == 1) {
                return false;
            }
            
            // 逻辑删除
            conversation.setIsDelete(1);
            conversation.setUpdateTime(new Date());
            return this.updateById(conversation);
            
        } catch (Exception e) {
            log.error("管理员删除对话失败，对话ID: {}", conversationId, e);
            return false;
        }
    }

    @Override
    public MessageListVO getAdminConversationDetail(Long conversationId) {
        try {
            Conversation conversation = this.getById(conversationId);
            if (conversation == null || conversation.getIsDelete() == 1) {
                return null;
            }
            
            MessageListVO vo = new MessageListVO();
            vo.setConversationId(conversationId);
            vo.setStatus(conversation.getStatus());
            vo.setCreateTime(conversation.getCreateTime());
            vo.setUpdateTime(conversation.getUpdateTime());
            
            // 解析消息
            List<ChatMessage> messages = new ArrayList<>();
            if (StringUtils.isNotBlank(conversation.getMessage())) {
                try {
                    messages = parseMessages(conversation.getMessage());
                } catch (Exception e) {
                    log.error("解析对话消息失败，对话ID: {}", conversationId, e);
                }
            }
            
            vo.setMessages(messages);
            vo.setTotalCount(messages.size());
            return vo;
            
        } catch (Exception e) {
            log.error("管理员获取对话详情失败，对话ID: {}", conversationId, e);
            return null;
        }
    }
}




